<template>
  <div>
    <div class="space-box">
      <h1 class="title">
        个人空间
      </h1>
      <a-form :model="userInfo" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="头像">
          <a-upload :file-list="fileList" :before-upload="beforeUpload" name="avatar" list-type="picture-card"
            class="avatar-uploader" :show-upload-list="false">
            <a-image :src="imageUrl" alt="avatar" :width="100" :height="100" :preview="false"
              fallback="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png">
            </a-image>
          </a-upload>
          <a-button type="primary" :disabled="true" :loading="uploading" style="margin-top: 16px">
            {{ uploading ? '上传中' : '未上传' }}
          </a-button>

        </a-form-item>
        <a-form-item label="用户名">
          {{ userInfo.name }}
        </a-form-item>
        <a-form-item label="用户类型">
          {{ userInfo.type === 1 ? "管理员" : "普通用户" }}
        </a-form-item>
        <a-form-item label="用户id">
          {{ userInfo.id }}
        </a-form-item>
        <a-form-item label="注册时间">
          {{ userInfo.regdate }}
        </a-form-item>
        <a-form-item label="操作">
          <!-- <a-button @click="checkLogin"> checklogin</a-button> -->
          <a-button style="margin-left: 10px" @click="logout">退出登录</a-button>
        </a-form-item>
      </a-form>

      <a-divider>修改密码</a-divider>
      <a-form :model="passwordForm" :label-col="labelCol" :wrapper-col="wrapperCol" @finish="handlePasswordChange"
        :validate-messages="validateMessages">
        <a-form-item hasFeedback name="oldPassword" label="旧密码" :rules="[{ required: true, message: '密码过短', min: 8 }]">
          <a-input-password v-model:value="passwordForm.oldPassword">
            <template #prefix>
              <LockOutlined class="site-form-item-icon" />
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item hasFeedback name="newPassword" label="新密码" :rules="[{ required: true, message: '密码过短', min: 8 }]">
          <a-input-password v-model:value="passwordForm.newPassword">
            <template #prefix>
              <LockOutlined class="site-form-item-icon" />
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item hasFeedback name="confirmPassword" label="确认密码"
          :rules="[{ required: true, message: '密码过短', min: 8 }]">
          <a-input-password v-model:value="passwordForm.confirmPassword">
            <template #prefix>
              <LockOutlined class="site-form-item-icon" />
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item label="操作">
          <a-button html-type="submit"> 确认修改</a-button>
        </a-form-item>
      </a-form>

    </div>
    <MyFooter></MyFooter>
  </div>

</template>
<script lang="ts">
import { LockOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { defineComponent, ref, onMounted } from 'vue';
import { useStore } from "vuex"
import { useRouter } from "vue-router"
import { uploadImage } from "@/api/image"
import { getUserInfo, changeAvatar, changePassword } from "@/api/user"
import MyFooter from '../components/MyFooter.vue';

export default defineComponent({
  components: {
    LockOutlined,
    MyFooter
    // PlusOutlined
  },
  setup() {
    let store = useStore()
    const router = useRouter()
    let imageUrl = ref("")
    let userInfo = ref({
      name: "",
      id: 0,
      imgpath: "",
      type: 0,
      regdate: ""
    })
    onMounted(() => {
      getUserInfo().then(res => {
        userInfo.value = res.data
        imageUrl.value = userInfo.value.imgpath
      })
    })

    const uploading = ref<boolean>(false);
    const formData = new FormData();

    const fileList = ref<any>([])
    const handleUpload = () => {
      uploading.value = true;
      changeAvatar(formData).then((res) => {
        fileList.value.pop();
        formData.delete('file');
        uploading.value = false;
        message.success('上传成功');
        //TODO:逻辑改
        imageUrl.value = res.data.imgpath
      }).catch(() => {
        uploading.value = false;
        message.error('上传失败');
      });
    };
    const beforeUpload: any = (file: any) => {
      fileList.value[0] = file
      formData.delete('file')
      formData.append('file', file as any);

      handleUpload()
      return false;
    };



    function checkLogin() {
      store.dispatch("checkAuthState")
    }

    function logout() {
      store.dispatch("logout")
      router.push("/login")
    }

    const passwordForm = ref({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    function handlePasswordChange() {
      console.log(passwordForm.value)
      if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
        message.error("请确认两次密码是否正确")
        return
      }
      changePassword({
        password: passwordForm.value.oldPassword,
        newPassword: passwordForm.value.newPassword
      }).then(res => {
        message.success("修改成功")
        passwordForm.value = {
          oldPassword: '',
          newPassword: '',
          confirmPassword: ''
        }
      })
    }

    const validateMessages = {
      required: '${label} 不能为空'
    };

    return {
      fileList,
      uploading,
      beforeUpload,
      handleUpload,
      imageUrl,
      checkLogin,
      logout,
      userInfo,
      labelCol: { style: { width: '100px' } },
      wrapperCol: { span: 14, style: { marginLeft: "10px" } },
      passwordForm,
      handlePasswordChange,
      validateMessages
    };
  },
});
</script>

<style lang="less" scoped>
.space-box {
  margin: 20px 20% 20px 5%;
  background-color: whitesmoke;
  padding: 5px;

  .title {
    font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
    font-size: 30px;
    text-align: center;
    margin-bottom: 8px;
  }

  .avatar {
    width: 100px;
    height: 100px;
  }
}
</style>
